package com.example.sixtrainingdemo.presenter;

import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.net.Uri;
import android.util.Log;

import com.example.sixtrainingdemo.contract.AddGoodsContract;
import com.example.sixtrainingdemo.entity.Goods;
import com.example.sixtrainingdemo.entity.Photo;

import java.util.List;

public class AddGoodsPresenter implements AddGoodsContract.IAddGoodsPresenter {

   private AddGoodsContract.IAddGoodsView mAddGoodsView;
   private Context mContext;

   public AddGoodsPresenter(AddGoodsContract.IAddGoodsView addGoodsView, Context context) {
      mAddGoodsView = addGoodsView;
      mContext = context;
   }

   @Override
   public void saveGoods(Goods goods) {
      new Thread(new Runnable() {
         @Override
         public void run() {
            //商品插入
            ContentValues cv = new ContentValues();
            cv.put("goods_name", goods.getName());
            cv.put("goods_price", goods.getPrice());
            cv.put("goods_unit", goods.getUnit());
            cv.put("goods_message", goods.getMessage());
            cv.put("goods_browse", 0);
            Uri goodsUrl = Uri.parse("content://com.example.sixtrainingdemo.provider/goods");
            Uri insertUri = mContext.getContentResolver().insert(goodsUrl, cv);
            long newRowId = ContentUris.parseId(insertUri);
            Log.d("", "新插入的商品id ===== " + newRowId);
            List<Photo> photoList = goods.getPhotoList();
            Log.d("", "photoList ===== " + photoList.size());
            ContentValues[] arrayValues = new ContentValues[photoList.size()];
            for (int i = 0; i < photoList.size() - 1; i++) {
               ContentValues contentValues = new ContentValues();
               contentValues.put("goods_id", newRowId);
               contentValues.put("image", photoList.get(i).getData());
               arrayValues[i] = contentValues;
               Log.d("", "arrayValues ===== " + i);
            }
            Uri photoUrl = Uri.parse("content://com.example.sixtrainingdemo.provider/photo");
            //批量插入图片
            int count = mContext.getContentResolver().bulkInsert(photoUrl,arrayValues);
            Log.d("", "count ===== " + count);
         }
      }).start();
   }
}
